import collections
import operator

def prod(factors):
    return reduce(operator.mul,factors, 1)

f=open('c:\python27\data.txt')
f.seek(0)
#count={}
features={}
featureNameList=[]
featureCounts= collections.defaultdict(int)
featureVectors=[]
predictCounts=collections.defaultdict(int)
predictResult={}
#for line in f:
#   a=line.split()
#  for word in a:
#     featureVectors.append(word)


for line in f:
    if line[0]!='@':
        featureVectors.append(line.strip('').strip('\n').lower().split(','))
    else:
        if line.strip(' ').lower().find('@data')==-1 and (not line.lower().startswith('@relation')):
            featureNameList.append(line.strip(' ').split()[1])
            features[featureNameList[len(featureNameList)-1]]=line[line.find('{')+1:line.find('}')].strip(' ').split(',')
                
f.close()

#print featureVectors
# print featureNameList
# print features

for fv in featureVectors:
    predictCounts[fv[len(fv)-1]]+=1                             # count number of occurence of class=yes and class= no in training set
    for counter in range(0,len(fv)-1):
        predictCounts[fv[counter]]+=1                           # count number of occurence of each attribute in the training set
        featureCounts[(fv[counter],fv[len(fv)-1])]+=1

print predictCounts

probClass=collections.defaultdict(int)
probClass[('c_yes')]=round(predictCounts[('c_yes')])/round(len(featureVectors))
probClass[('c_no')]=round(predictCounts[('c_no')])/round(len(featureVectors))
for fv in featureVectors:
    for i in range(0,len(fv)-1):
        probClass[(fv[i])]=round(predictCounts[(fv[i])])/(len(featureVectors))

print probClass
# for fv in featureVectors:
#     for a in range(len(fv)):
#         predictCounts[fv[a]]+=1
# X=['senior','medium','no','fair','c_yes']  
X=['youth','medium','yes','fair','c_yes']                                    # given instance of new sample

# for fi in X:
#     print featureCounts[(fi,X[len(X)-1])]
    
prob_features=collections.defaultdict(int)
      
for fi in X:
    prob_features[(fi,X[len(X)-1])]=round(featureCounts[(fi,X[len(X)-1])])/(predictCounts[(X[len(X)-1])])
    #print prob_features[(fi,X[len(X)-1])]
#print predictCounts[X[len(X)-1]]

prob_predict=collections.defaultdict(int)
"""initialize the probability of each value as 1"""

for i in X:
    prob_predict[(X[len(X)-1],i)]=1
    
for i in X:
    for counter in range(len(X)-2):
        prob_predict[(X[len(X)-1],i)]*=prob_features[(X[counter],X[len(X)-1])]
    #print probClass[(i)]    
    prob_predict[(X[len(X)-1],i)]=prob_predict[(X[len(X)-1],i)]*probClass[(X[len(X)-1])]/probClass[(i)]   # compute posterior probability

predictResult=max(prob_predict)    

print predictResult   
   # prob_predict[(X[len(X)-1],i)]*=probClass[X[len(X)-1]]/probClass[(X[counter])]
#print prob_predict
"""Probability of give instance X is computed as"""

 